package com.yeyks.web;

import com.yeyks.account.dal.domain.AccountInfo;
import com.yeyks.account.utils.AccountUtil;
import com.yeyks.annotation.NeedToken;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.commonReference.service.account.AccountInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author fuchangshuai
 * @date 2019/05/07 10:52
 * 基于自定义注解实现token验证
 */
@Component(value = "tokenInterceptor")
@Slf4j
public class TokenInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private AccountInfoService accountService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //如果不是映射到方法直接通过，如果映射了就获取到当前请求对应Controller的方法
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        NeedToken needToken = method.getAnnotation(NeedToken.class);
        //如果带noToken注解，则不需要验证token，直接过掉
        if (needToken == null) {
            return true;
        }
        String token = request.getHeader("token");
        if (null == token || token.trim().equals("")) {
            token = request.getHeader("headerToken");
            if (null == token || token.trim().equals("")) {
                throw new ServiceException("token不能为空");
            }
        }
        try {
            AccountInfo operatorInfo = accountService.token2AccountInfo(token);
            request.setAttribute("loginUser", operatorInfo);
            AccountUtils.putLoginUser(operatorInfo);
        } catch (ServiceException e) {
            log.warn("拦截器通过token查询异常, {},{}", e.getMessage(),request.getRequestURL().toString());
            throw new ServiceException(e.getCode(), e.getMessage());
        }
        return true;
    }
}
